//
//  MYGCollectListViewController.swift
//  MYDoctor
//
//  Created by Denny on 2024/3/18.
//

import UIKit
import JXSegmentedView
import MJRefresh

class MYGCollectListViewController: UIViewController,JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
    
    var keyWords = ""
    var page = 1
    var dataSource = [MYGCollectlistModel]()
    var newsDataSource = [MYGIndInfoModel]()
    var topicDataSource = [MYGTopicModel]()
    
    var type = 0
    var fromMain = false//首页搜索进来
    lazy var tableView: UITableView = {
        let control = UITableView()
        control.rowHeight = 105
        control.separatorStyle = .none
        control.dataSource = self
        control.delegate = self
        control.register(UINib.init(nibName: "MYGMyCollectionTableViewCell", bundle: nil), forCellReuseIdentifier: "MYGMyCollectionTableViewCell")
        control.register(UINib.init(nibName: "MYGTopicTableViewCell", bundle: nil), forCellReuseIdentifier: "MYGTopicTableViewCell")
        control.register(cellWithClass: MYGAcademicCollectCell.self)
        control.register(cellWithClass: MYGIndInfoTableViewCell.self)
        control.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            
            self?.refreshData()
        })
        
        
        control.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.refreshData()
        })
        return control
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if fromMain == false {
            refreshData()
        }
       
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.tableView)
        refreshData()
        self.tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData(_:)), name: Notification.Name("MYGCollectListViewController_refreshData"), object: nil)
    }
    
   @objc func reloadData(_ sender:Notification) {
        if let text = sender.object as? String {
            keyWords = text
            refreshData()
        }
    }
    
    func refreshData() {
        if fromMain {
            if type == 6 {
                getnews()
            }
            
            if type == 1 {
                getTopicData()
            }
        }else {
            MYGLoading.show()
            MYGNetwork<MYGMeAPI, MYGPageModel<MYGCollectlistModel>>.request(target: .myCollectList(param: [
                "type":"\(self.type)","pageSize":"20",
                "page":String(format: "%d", page),])) {[weak self] item in
                    guard let `self` = self else {return}
//                    MYGLoading.hide()
//                    self.dataSource = item.list
//                    self.tableView.reloadData()
//                    self.tableView.mj_header?.endRefreshing()
//                    self.tableView.mj_footer?.endRefreshing()
                    
                    if self.page == 1{
                        self.dataSource.removeAll()
                    }
                    self.dataSource.append(contentsOf: item.list)
                    self.tableView.reloadData()
                    MYGLoading.hide()
                    self.tableView.mj_header?.endRefreshing()
                    if item.page.total <= self.dataSource.count {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                } failed: { _, error in
                    MYGLoading.hide()
                    self.tableView.mj_header?.endRefreshing()
                    self.tableView.mj_footer?.endRefreshing()
                    MMYGHUD.showToast(text: error)
                }
        }
    }
    
    
    func getnews() {
        MYGLoading.show()
        MYGNetwork<MYGHomePageAPI, MYGPageModel<MYGIndInfoModel>>.request(target: .getIndInfoList(param: [
            "key":keyWords,
            "pageSize":"20",
            "page":String(format: "%d", page),
            "sort":"1"])) {[weak self] item in
                MYGLoading.hide()
                if self?.page == 1{
                    self?.newsDataSource.removeAll()
                }
                self?.newsDataSource.append(contentsOf: item.list)
                self?.tableView.reloadData()
                MYGLoading.hide()
                self?.tableView.mj_header?.endRefreshing()
                if item.page.total <= self?.newsDataSource.count ?? 0 {
                    self?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self?.tableView.mj_footer?.endRefreshing()
                }
            } failed: {[weak self] _, error in
                self?.tableView.mj_header?.endRefreshing()
                self?.tableView.mj_footer?.endRefreshing()
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
    }
    
    func getTopicData() {
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGTopicModel>>.request(target: .articleTopicList(param: [
            "page":"\(self.page)",
            "pageSize":"20",
            "key":keyWords,
            "sort":"1"])) { item in
                MYGLoading.hide()
                self.tableView.mj_header?.endRefreshing()
                if item.page.page == 1 {
                    self.topicDataSource = item.list
                } else {
                    self.topicDataSource.append(contentsOf: item.list)
                }
                
                
                if item.page.total <= self.topicDataSource.count {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self.tableView.mj_footer?.endRefreshing()
                }
                
                self.tableView.reloadData()
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
    }
    
   private func canelCollect(id:Int) {
        var params:[String:Any] = [:]
        params["collect_status"] = "0"//1收藏 0取消收藏
        params["data_id"] = id
        params["type"] = "2"
       
       MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .collectSubmit(param: params)) { [self] item in
            MYGLoading.hide(self.view)
            refreshData()
        } failed: { _, error in
            MYGLoading.hide(self.view)
            MMYGHUD.showToast(text: error)
       }
    }
}

extension MYGCollectListViewController: UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.type == 6 {
            //新闻
            let cell = tableView.dequeueReusableCell(withIdentifier: "MYGIndInfoTableViewCell", for: indexPath) as! MYGIndInfoTableViewCell
            if fromMain {
                let model = self.newsDataSource[indexPath.row]
                cell.modelIn = model
            }else {
                let model = self.dataSource[indexPath.row]
                cell.modelIn = model.news
            }
            
            return cell
        }
        if self.type == 1 {
            //话题
            let cell = tableView.dequeueReusableCell(withIdentifier: "MYGTopicTableViewCell", for: indexPath) as! MYGTopicTableViewCell
            if fromMain {
                let model = self.topicDataSource[indexPath.row]
                cell.bindData(model)
            }else {
                let model = self.dataSource[indexPath.row]
                cell.bindData(model.topic)
            }
            
            return cell
        }
        
        if self.type == 2 {
            let cell = tableView.dequeueReusableCell(withClass: MYGAcademicCollectCell.self)
            let model = self.dataSource[indexPath.row]
            cell.bindData(model.speech)
            cell.clickCollectBlock = {[weak self] id in
                self!.canelCollect(id: id)
            }
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGMyCollectionTableViewCell", for: indexPath) as! MYGMyCollectionTableViewCell
//                let model = self.dataSource[indexPath.row]
//                cell.bindData(model)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.type == 6 {
            return 200
        }else if self.type == 1 {
            return 170
        }else if type == 2 {
            let model = self.dataSource[indexPath.row].speech
            var names:[String] = []
            names.append("\(model.speechCn)")
            names.append("\(model.speechEn)")
            model.expert.forEach{ obj in
                names.append("\(obj.expertCn)(\(obj.hospital)/\(obj.expertEn)")
            }
            names.append("\(model.room.sessionCn)-\(model.room.sessionDate)-\(model.room.roomCn)")
            let h = CGFloat(names.count * 20)
            return h + 35
        }
        return 105
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if fromMain {
            if type == 6 {
                return newsDataSource.count
            }else {
                return topicDataSource.count
            }
        }
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.type == 1 {
            let vc = MYGTopicDetailViewController()
            if fromMain {
                let model = self.topicDataSource[indexPath.row]
                vc.id = model.id
            }else{
                let model = self.dataSource[indexPath.row]
                vc.id = model.topic.id
            }
         
            self.navigationController?.pushViewController(vc, animated: true)
        }
        if self.type == 6 {
            let vc = MYGIndInfoDetailViewController()
            if fromMain {
                let model = self.newsDataSource[indexPath.row]
                vc.id = model.id
            }else {
                let model = self.dataSource[indexPath.row]
                vc.id = model.news.id
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}
